﻿var dojoWrapper = new wDojo();
dojoWrapper.SetObject("SSVC.Wrap.Dojo", dojoWrapper);

SSVC.Wrap.Dojo.RegisterModulePath("javascript", top.aras.getInnovatorUrl() + "Client/Modules/aras.innovator.SSVC/javascript");
SSVC.Wrap.Dojo.RegisterModulePath("scripts", top.aras.getInnovatorUrl() + "Client/Modules/aras.innovator.SSVC/scripts");

Utils =
{
	StaticStr:
		{
			fillShapeRgbValue: "rgba(255, 255, 255, 0)",
			namespaceURI: "http://www.w3.org/2000/svg",
			textFontFamily: "Arial"
		},

	Page:
	{
		Style: function(stylename, stylestring)
		{
			this.StyleName = "";
			this.StyleString = "";

			this.addStyle = function()
			{
				this.StyleName = (stylename) ? stylename : "cssClass" + SSVC.Utils.MakeName(5);
				this.StyleString = stylestring;

				var styleSheets = document.styleSheets[0];
				if (styleSheets.insertRule)
				{
					styleSheets.insertRule("." + this.StyleName + "{" + this.StyleString + "}", styleSheets.cssRules.length);
				}
				else
				{
					styleSheets.addRule(this.StyleName, this.StyleString, styleSheets.cssRules.length);
				}
				return this;
			};

			this.getStyle = function(selectorName)
			{
				var rules = document.styleSheets[0].cssRules;
				selectorName = "." + selectorName;

				var style = SSVC.Utils.Page.GetStyleBySelectorText(selectorName);
				if (style !== undefined)
				{
					this.StyleString = style.cssText.matchRegExp(/(?:{.*?})/);
					this.StyleName = style.selectorText.ltrim();
					return this;
				}
				return null;
			};

			this.addHoverStyle = function(stylestring)
			{
				return new SSVC.Utils.Page.Style(this.StyleName + ":hover", stylestring).addStyle();
			};

			this.addStyle();
		},

		GetStyleBySelectorText: function(selectorText, fileClass)
		{
			var rules;
			if (fileClass)
			{
				for (var i = 0; i < document.styleSheets.length; i++)
				{
					if (document.styleSheets[i].href.indexOf(fileClass) !== -1)
					{
						rules = document.styleSheets[i];
						break;
					}
				}
			}
			else
				rules = document.styleSheets[0].cssRules;

			for (var j in rules)
			{
				if (rules[j].selectorText === selectorText)
				{
					return rules[j];
				}
			}
			return null;
		},

		IsPostBack: (Object.keys(SSVC).length > 2) ? true : false,

		ViewerMode: +0,

		LoadModules: function(strArr)
		{
			var newarr = [];
			if (typeof strArr === "object")
			{
				for (var i = 0; i < strArr.length; i++)
				{
					if (SSVC[strArr[i]] === undefined)
						newarr.push("javascript/" + strArr[i]);
				}
			}
			else
				newarr = strArr;

			SSVC.Wrap.Dojo.Require(newarr);
		},

		LoadGeometry: function()
		{
			this.LoadModules(["Geometry", "SvgElement", "SvgTextElement", "SvgLineElement", "SvgEllipseElement", "SvgLabelElement", "SvgScribbleElement", "SvgContainer"]);
		},

		GetInstanceDocument: function()
		{
			if (!top.instance) return;
			return Utils.isIE() ? top.instance.document : top.instance.contentDocument;
		},

		IncludeFile: function(path, type)
		{
			if (type === "css")
			{
				var head_node = document.getElementsByTagName("head")[0];
				var link_tag = document.createElement("link");
				link_tag.setAttribute("rel", "stylesheet");
				link_tag.setAttribute("type", "text/css");
				link_tag.setAttribute("href", path);
				head_node.appendChild(link_tag);
			}
		},

		getScrollbarWidth: function()
		{
			var outer = document.createElement("div");
			outer.style.visibility = "hidden";
			outer.style.width = "100px";
			outer.style.msOverflowStyle = "scrollbar";

			document.body.appendChild(outer);

			var widthNoScroll = outer.offsetWidth;
			// force scrollbars
			outer.style.overflow = "scroll";

			// add innerdiv
			var inner = document.createElement("div");
			inner.style.width = "100%";
			outer.appendChild(inner);

			var widthWithScroll = inner.offsetWidth;

			// remove divs
			outer.parentNode.removeChild(outer);

			return widthNoScroll - widthWithScroll;
		},

		EncodeHTML: function(html)
		{
			if (!html)
				return "";

			var encodedHTML = html.replace(/&/g, "&amp");
			encodedHTML = encodedHTML.replace(/"/g, "&quot");
			encodedHTML = encodedHTML.replace(/'/g, "&#39");
			encodedHTML = encodedHTML.replace(/</g, "&lt;");
			encodedHTML = encodedHTML.replace(/>/g, "&gt;");
			return encodedHTML;
		}
	},

	Enums:
	{
		DocumentMode:
		{
			Feed: +0,
			PDF: +1,
			CAD: +2,
			Image: +3
		},

		SortMode:
		{
			Conversation: "converstaion",
			Date: "date",
			FirstName: "first_name",
			LastName: "last_name",
			Message: "message",
			File: "file",
			FileAndPage: "file_and_page"
		},

		DisplayMode:
		{
			Standard: "standard",
			Review: "review"
		},

		ViewerMode:
		{
			MarkupCreation: +0,
			MarkupReview: +1,
			MarkupSelect: +2,
			View: +3
		},

		// Selected area tops:
		//  1........7........4
		//  .                 .
		//  .                 .
		//  2                 5
		//  .                 .
		//  .                 .
		//  3........8........6

		ResizingSides:
		{
			LEFT: +2,
			RIGHT: +5,
			TOP: +7,
			BOTTOM: +8,
			LEFT_TOP: +1,
			RIGHT_TOP: +4,
			LEFT_BOTTOM: +3,
			RIGHT_BOTTOM: +6
		},

		ElementType:
		{
			ELLIPSE: "ellipse",
			RECT: "rect",
			LINE: "line",
			TEXT: "text"
		},

		ResizingTops:
		{
			top1: "TopLeftCircleResizeElement",
			top2: "MiddleLeftCircleResizeElement",
			top3: "BottomLeftCircleResizeElement",
			top4: "TopRightCircleResizeElement",
			top5: "MiddleRightCircleResizeElement",
			top6: "BottomRightCircleResizeElement",
			top7: "TopMiddleCircleResizeElement",
			top8: "BottomMiddleCircleResizeElement",

			topLeft: "Circle1ResizeElement",
			topRight: "Circle2ResizeElement"
		},

		ActionMode:
		{
			Resizing: +1,
			Moving: +2,
			Deactivate: +3
		},

		AffectedKey:
		{
			SHIFT: 16,
			CTRL: 17,
			ENTER: 13,
			ALT: 18,
			ESCAPE: 27
		},

		Cursors:
		{
			Move: "move",
			Default: "default"
		}
	},

	LoadPageScripts: function()
	{
		SSVC.Utils.Page.ViewerMode = (function()
		{
			switch (document.title)
			{
				// TODO: move to pages or item actions
				case "HOOPS":
					return SSVC.Utils.Enums.DocumentMode.CAD;
				case "PDF":
					return SSVC.Utils.Enums.DocumentMode.PDF;
				case "image":
					return SSVC.Utils.Enums.DocumentMode.Image;
				default:
					return SSVC.Utils.Enums.DocumentMode.Feed;
			}
		})();

		switch (SSVC.Utils.Page.ViewerMode)
		{
			case SSVC.Utils.Enums.DocumentMode.Feed:
				Utils.Page.LoadModules(["UserHelper", "Select", "TemplateControl", "Feed", "FeedEventHandler", "FeedToolbar", "FilterPopup", "ReplyToolbar", SSVC.VisualCollaborationTool.Preferences.MessageTemplatesArr[0], SSVC.VisualCollaborationTool.Preferences.UserInfoTemplate]);
				break;
			case SSVC.Utils.Enums.DocumentMode.CAD:
				Utils.Page.LoadGeometry();
				Utils.Page.LoadModules(["UserHelper", "PDFjsWrapper", "mtButton", "MarkupToolbar", "MarkupViewer", "MarkupPage"]);
				break;
			case SSVC.Utils.Enums.DocumentMode.PDF:
				Utils.Page.LoadGeometry();
				Utils.Page.LoadModules(["UserHelper", "PDFjsWrapper", "mtButton", "MarkupToolbar", "MarkupViewer", "MarkupPage"]);
				break;
			case SSVC.Utils.Enums.DocumentMode.Image:
				Utils.Page.LoadGeometry();
				Utils.Page.LoadModules(["UserHelper", "PDFjsWrapper", "mtButton", "MarkupToolbar", "MarkupViewer", "MarkupPage"]);
				break;
		}
	},

	GetResource: function(key)
	{
		return top.aras.getResource("../Modules/aras.innovator.ssvc/", key);
	},

	isIE: function()
	{
		return SSVC.Wrap.Dojo.Has("ie") !== undefined;
	},

	isFirefox: function()
	{
		return SSVC.Wrap.Dojo.Has("ff") !== undefined;
	},

	isChrome: function()
	{
		return window.chrome ? true : false;
	},

	isNotNullOrUndefined: function(varObject)
	{
		return ((typeof varObject !== "undefined") && (varObject !== null));
	},

	isNullOrUndefined: function(obj)
	{
		return ((typeof obj === "undefined") || (obj === null));
	},

	GetDateTimeInNeutralFormat: function(dateTimePar)
	{
		function pad(x)
		{
			return (x < 10) ? "0" + x : "" + x;
		}

		var cntx = top.aras.newIOMInnovator().getI18NSessionContext();
		var corporateToLocalOffset = cntx.GetCorporateToLocalOffset();

		var dateTime = dateTimePar !== undefined ? dateTimePar : new Date();
		//Convert to Corporate Time
		dateTime.setMinutes(dateTime.getMinutes() + corporateToLocalOffset);

		var months = dateTime.getMonth() + 1;
		var days = dateTime.getDate();
		var years = dateTime.getFullYear();
		var hours = dateTime.getHours();
		var minutes = dateTime.getMinutes();
		var seconds = dateTime.getSeconds();
		var ampm = (hours >= 12 ? "PM" : "AM");
		hours = hours % 12;
		hours = hours ? hours : 12; // the hour "0" should be "12"

		var dateTimeStr = pad(months) + "/" + pad(days) + "/" + years + " " + pad(hours) + ":" + pad(minutes) + ":" + pad(seconds) + " " + ampm;
		return cntx.ConvertToNeutral(dateTimeStr, "date", "short_date_time");
	},

	MakeName: function(length)
	{
		var text = "";
		var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

		for (var i = 0; i < length; i++)
			text += possible.charAt(Math.floor(Math.random() * possible.length));

		return text;
	},

	convertHexToRGBA: function(hexColor, alpha)
	{
		var color = new SSVC.Wrap.Dojo.Color(hexColor);
		var res = color.toRgb();
		return "rgba(" + res[0] + "," + res[1] + "," + res[2] + "," + alpha + ")";
	}
};

//Extensions

if (!String.prototype.IsNullOrEmpty)
{
	String.prototype.IsNullOrEmpty = function()
	{
		return (SSVC.Utils.isNullOrUndefined(this) || (this === ""));
	};
}

if (!String.prototype.ltrim)
{
	String.prototype.ltrim = function()
	{
		return this.replace(/^\.+/, "").replace(/^\s+/, "");
	};
}

if (!String.prototype.trim)
{
	String.prototype.ltrim = function()
	{
		return this.replace(/^\s+|\s+$/g, "");
	};
}
if (!String.prototype.matchRegExp)
{
	String.prototype.matchRegExp = function(regexp)
	{
		var VRegExp = new RegExp(regexp);
		var VResult = this.match(VRegExp);
		return VResult;
	};
}

if (!String.prototype.Format)
{
	String.prototype.Format = function()
	{
		var args = arguments;
		return this.replace(/{(\d+)}/g, function(match, number)
		{
			return typeof args[number] !== "undefined" ? args[number] : "";
		});
	};
}

if (!Array.prototype.Find)
	Object.defineProperty(Array.prototype, "Find",
		{
			value: function(param, value)
			{
				for (var i = 0; i < this.length; i++)
				{
					var entry = this[i];
					if (entry[param] === value)
						return entry;
				}
			}
		});

if (!Array.prototype.Remove)
	Object.defineProperty(Array.prototype, "Remove",
		{
			value: function(param, value)
			{
				this.forEach(function(entry)
				{
					if (entry[param] === value)
						this.splice(this.indexOf(entry), 1);
				});
			}
		});

if (!Array.prototype.FindAll)
	Object.defineProperty(Array.prototype, "FindAll",
		{
			value: function(param, value)
			{
				var list = [];
				this.forEach(function(entry)
				{
					if (entry[param] === value)
						list.push(entry);
				});
				return list;
			}
		});

if (!Array.prototype.FindDepth)
{
	Object.defineProperty(Array.prototype, "FindDepth",
		{
			value: function(param, childsProperyName, value)
			{
				for (var i = 0; i < this.length; i++)
				{
					var entry = this[i];
					if (entry[param] === value)
					{
						return entry;
					}
					else
					{
						var result = entry[childsProperyName].Find(param, value);
						if (result)
							return result;
					}
				}
				return null;
			}
		});
}

if (!Array.prototype.PushRange)
{
	Object.defineProperty(Array.prototype, "PushRange",
		{
			value: function(array)
			{
				var self = this;
				array.forEach(function(entry)
				{
					self.push(entry);
				});
			}
		});
}

if (!Array.prototype.GetIndex)
{
	Object.defineProperty(Array.prototype, "GetIndex",
		{
			value: function(element, strProperty)
			{
				for (var i in this)
				{
					if (this[i][strProperty] === element[strProperty])
						return i;
				}
				return -1;
			}
		});
}

if (!Array.prototype.IsExist)
{
	Object.defineProperty(Array.prototype, "IsExist",
		{
			value: function(element, property)
			{
				var index = this.GetIndex(element, property);
				if (index === -1) return false;
				else return true;
			}
		});
}

Utils.Page.ViewerMode = Utils.Enums.DocumentMode.Feed;

//load common modules
SSVC.Wrap.Dojo.SetObject("SSVC.Utils", Utils);
SSVC.Utils.Page.LoadModules(["ArasHelper", "VisualCollaborationTool", "Message"]);